<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Button type="primary" @click="handleAllocation()">新增</Button>
      <Table
        size="small"
        :loading="tableLoading"
        row-key="id"
        :columns="columns"
        :data="data"
        class="ivu-mt-16"
      >
        <template slot-scope="{ row }" slot="status">
          <Button
            v-if="row.status === '1'"
            type="success"
            size="small"
            @click="changeStatus(row)"
            >启用</Button
          >
          <Button
            v-if="row.status === '0'"
            type="error"
            size="small"
            @click="changeStatus(row)"
            >停用</Button
          >
        </template>
        <template slot-scope="{ row }" slot="operation">
          <a @click="handleAllocation(row)">编辑</a>
          <Divider type="vertical" v-if="hqdelete" />
          <a @click="delfun(row)" v-if="hqdelete" class="deleteBtn">删除</a>
        </template>
      </Table>
      <div class="ivu-mt ivu-text-center">
        <Page
          :total="total"
          :current.sync="page"
          show-total
          show-elevator
          :page-size="pageSize"
          @on-change="changePage"
          :page-size-opts="pageOpts"
          show-sizer
          transfer
          @on-page-size-change="changePageSize"
        />
      </div>
    </Card>
    <Modal
      v-model="modal"
      :title="edit ? '编辑' : '新增'"
      :mask-closable="false"
      draggable
      @on-cancel="handleDrawerCancel()"
    >
      <Form
        :model="formItem"
        :rules="ruleValidate"
        ref="formItem"
        :label-width="80"
      >
        <FormItem label="名称" prop="input">
          <Input
            v-model="formItem.input"
            placeholder="请输入来源名称,批量新增用逗号分隔"
            clearable
          ></Input>
        </FormItem>
        <FormItem label="排序" prop="number">
          <Input
            v-model="formItem.number"
            type="number"
            placeholder="默认在现在排序后+1"
          ></Input>
        </FormItem>
        <FormItem label="父节点" prop="select">
          <Select v-model="formItem.select" placeholder="默认根节点" clearable>
            <Option
              v-for="(item, index) in fatherList"
              :key="index"
              :value="item.id"
              >{{ item.source_name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem v-if="edit" label="状态" prop="switch">
          <i-switch v-model="formItem.switch" clearable>
            <span slot="open">On</span>
            <span slot="close">Off</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleDrawerCancel()">取消</Button>
        <Button
          type="primary"
          :loading="loading"
          @click="handleSubmit('formItem')"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  GetChannelList,
  GetChannelParentList,
  CreateChannel,
  UpdateChannel,
  UpdateChannelStatus,
} from "@api/setting";
import { marketingsourcechanneltruedelete } from "@api/delete";
import { mapState } from "vuex";

export default {
  data() {
    return {
      modal: false,
      edit: false,
      loading: false,
      tableLoading: false,
      formItem: {
        input: "",
        select: "",
        number: "",
        switch: true,
      },
      ruleValidate: {
        input: [{ required: true, message: "渠道名不可为空", trigger: "blur" }],
      },
      columns: [
        {
          title: "名称",
          key: "source_name",
          tree: true,
        },
        {
          title: "排序",
          key: "sort",
        },
        {
          title: "状态",
          slot: "status",
        },
        {
          title: "操作",
          slot: "operation",
        },
      ],
      data: [],
      fatherList: [],
      page: 1,
      pageSize: 10,
      total: 0,
      hqdelete: false,
      pageOpts: [10, 20, 30, 50],
    };
  },
  computed: {
    ...mapState(["admin"]),
    projectId() {
      return this.admin.user.info.project_id;
    },
  },
  created() {
    this.onLoad();
    this.state = JSON.parse(localStorage.getItem("poweredit"));
    for (let item of this.state) {
      if (item.name === "来源渠道真删除") {
        this.hqdelete = item.bool;
      }
    }
  },
  methods: {
    delfun(row) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "删除后已绑定的数据将被清空，是否确认删除？",
        onOk: () => {
          marketingsourcechanneltruedelete({ id: row.id }).then((res) => {
            this.$Message.info("删除成功");
            this.onLoad();
          });
        },
        onCancel: () => {},
      });
    },
    getFatherList() {
      /**
       * @description 渠道一级列表
       */
      this.tableLoading = true;
      GetChannelParentList()
        .then((res) => {
          this.fatherList = res;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    onLoad() {
      /**
       * @description 渠道列表
       * @param {Object} param page  {String} 页数
       * @param {Object} param pageSize {String} 条数/页
       */
      const params = this.getParam();
      GetChannelList(params)
        .then((res) => {
          this.data = res.list;
          this.page = res.page;
          this.pageSize = res.pageSize;
          this.total = res.total;
        })
        .catch((err) => {
          console.log(err);
        });

      this.getFatherList();
    },
    getParam() {
      let params = {
        page: this.page,
        pageSize: this.pageSize,
      };
      return params;
    },
    changePage(page) {
      this.page = page;
      this.onLoad();
    },
    changePageSize(e) {
      this.pageSize = e;
      this.onLoad();
    },
    handleAllocation(row) {
      this.modal = true;
      if (row) {
        this.edit = true;
        // console.log(row)
        this.formItem = {
          input: row.source_name,
          select: row.pid,
          number: row.sort,
          switch: row.status === "1",
          id: row.id,
        };
      }
    },
    changeStatus(row) {
      const param = {
        id: row.id,
        status: row.status === "1" ? "0" : "1",
      };
      this.$Modal.confirm({
        title: "切换渠道状态",
        content: "确定" + (row.status === "1" ? "停用" : "启用") + "当前渠道?",
        onOk: () => {
          this.changeSubmit(param);
        },
        onCancel: () => {
          console.log("取消切换");
        },
      });
    },
    handleDrawerCancel() {
      this.modal = false;
      this.edit = false;
      this.$refs["formItem"].resetFields();
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.loading = true;
          const params = {
            source_name: this.formItem.input,
            pid: this.formItem.select || "0",
            sort: this.formItem.number,
            status: this.formItem.switch ? "1" : "0",
            project_id: this.projectId,
          };
          if (this.edit) {
            params.id = this.formItem.id;
            this.updateSubmit(params);
          } else {
            this.createSubmit(params);
          }
        } else {
          console.log("表单校验失败！");
        }
      });
    },
    createSubmit(params) {
      CreateChannel(params)
        .then(() => {
          this.$Message.success(" 创建成功");
          this.loading = false;
          this.onLoad();
          this.handleDrawerCancel();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    updateSubmit(params) {
      UpdateChannel(params)
        .then(() => {
          this.$Message.success(" 修改成功");
          this.loading = false;
          this.onLoad();
          this.handleDrawerCancel();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    changeSubmit(params) {
      UpdateChannelStatus(params).then(() => {
        this.$Message.success("状态切换成功");
        this.onLoad();
      });
    },
  },
};
</script>
<style scoped>
.deleteBtn {
  color: #ed4014;
  margin: 0 10px;
}
</style>
